<?php

namespace App\Http\Controllers;

use App\EmployeeDetail;
use App\loan_customer;
use App\Record;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Relations;
use Auth;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $sum = loan_customer::pluck('money')->sum();
        $num = User::all()->count();
        $order_num = loan_customer::all()->count();
        $pass = loan_customer::where('status',1)->get() ;

        if($pass){
            $benefit=$pass->pluck('repayment')->sum();
        }

        // 表格 1 数据
        $thisMonth = date('Y-m-01 00:00:00', strtotime('+1 month'));

        $year = date('Y-m-d 00:00:00', strtotime("$thisMonth -1 year"));

        $data1 = [
            'month' => [],
            'data' => [],
        ];

        $records = Record::whereBetween('created_at', [$year, $thisMonth])
            ->where('moneys', '>', 0)
            ->with('loans')
            ->get();

        for ($i = 0; $i < 12; $i++) {
            $tmp = strtotime("$year +$i month");
            $data1['month'][] = date('Y年m月', $tmp);
            $days = date('t', $tmp);
            $month = date('m', $tmp);
            $tmpData = 0;
            $start = date("Y-{$month}-01 00:00:00", $tmp);
            $end = date("Y-{$month}-{$days} 23:59:59", $tmp);

            foreach ($records as $v) {
                if ($v->created_at >= $start && $v->created_at <= $end) {
                    $tmpData += $v->moneys - $v->loans->money / $v->loans->limits;
                }
            }

            $data1['data'][] = number_format($tmpData, 2, '.', '');

        }

        // 表格 2 数据
        $loans = loan_customer::where('status', 1)->get();

        $level = [
            [
                'name' => '短期（一年）',
                'type' => 1,
            ],
            [
                'name' => '中期（三年）',
                'type' => 3,
            ],
            [
                'name' => '长期（五年）',
                'type' => 5,
            ],
        ];

        $data2 = [];

        foreach ($level as $item) {
            $tmp = [
                'name' => $item['name'],
                'value' => 0,
            ];

            foreach ($loans as $v) {
                if ($v->data_type == $item['type']) {
                    $tmp['value']++;
                }
            }

            $data2[] = $tmp;
        }


        // 表格 3 数据
        $level = [
            [
                'name' => '10 万以下',
                'min' => 0,
                'max' => 100000
            ],
            [
                'name' => '10 万到 50 万',
                'min' => 100000,
                'max' => 500000
            ],
            [
                'name' => '50 万以上',
                'min' => 500000,
                'max' => 50000000
            ],
        ];

        $data3 = [
            'money' => [],
            'people' => [],
        ];

        foreach ($level as $item) {
            $data3['money'][] = $item['name'];
            $tmp = 0;

            foreach ($loans as $v) {
                if ($v->money >= $item['min'] && $v->money <= $item['max']) {
                    $tmp++;
                }
            }

            $data3['people'][] = $tmp;
        }

//        dd($data1);

        \JavaScript::put([
            'data1' => $data1,
            'data2' => $data2,
            'data3' => $data3,
        ]);


        return view('home1',compact(['sum','num','order_num','benefit']));
    }

    public function employee()
    {
        $employee = EmployeeDetail::paginate(8);
//         EmployeeDetail::whereNotIn('id', [1])->delete();
//        dd($employee);exit;
        $user =User::where('auth', 3)->first();
//        Auth::user->id();
//        dd($user);
        return view('employee', [
//            '$employee'=>'employee',
            'employee' => $employee,
            'user' => $user
        ]);
    }

    public function employee_edit()
    {
        return view('employee_edit');
    }

    public function customer()
    {
        $list=loan_customer::paginate();
//        dd($list);exit;
        $filtration=loan_customer::where('state',1)->paginate(5);
//        dd($filtration);exit;
        $uid = Auth::user()->id;
        $auth = User::where('id',$uid)->value('auth');
//        loan_customer::whereNotIn('id', [1])->delete();
        return view('customer',compact('list','filtration','auth'));
    }


    public function add_employee(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
            'tel' => 'required',
            'birth' => 'required',
            'post' => 'required',
            'department' => 'required',
        ], [
            'name.required' => '姓名必须要填写',
        ]);

        $status = EmployeeDetail::create($request->except('_token'));
        if ($status) {
            return back()->with('success', '新增成功');
        } else {
            return back()->with('danger', '新增失败');
        }

    }

    public function update_employee($id)
    {
        $info = EmployeeDetail::where('id', $id)->first();
//        dd($info);exit;
        if (!$info) {
            return response()->json(['code' => '1001', 'msg' => '参数错误']);
        } else {
            return response()->json(['code' => '1000', 'data' => view('employee_edit', ['info' => $info,])->render(),]);
        }
    }

    public function update_employees(Request $request, $id)
    {

        $this->validate($request, [
            'name' => 'required',
            'tel' => 'required',
            'birth' => 'required',
            'post' => 'required',
            'department' => 'required',
        ]);

        $updatas = EmployeeDetail::where('id', $id)->update($request->except('_token'));
        if ($updatas) {
            return back()->with('success', '修改成功');
        } else {
            return back()->with('danger', '修改失败');
        }
    }

    public function employeeDestroy($id)
    {
        if (EmployeeDetail::where('id', $id)->delete()) {
            return back()->with('success', '删除成功');
        } else {
            return back()->with('danger', '删除失败');
        }
    }

    public function check_name(Request $request)
    {
        $data = $request->except('_token');
        $name = $data ['name'];
        $status = EmployeeDetail::where('name', $name)->first();
        if (!$status) {
            return response()->json(true);
        } else {
            return response()->json(false);
        }
    }

    public function check_tel(Request $request)
    {
        $data = $request->except('_token');
        $tel = $data ['tel'];
        $status = EmployeeDetail::where('tel', $tel)->first();
        if (!$status) {
            return response()->json(true);
        } else {
            return response()->json(false);
        }
    }

}
